package com.odm.communitymanage.ui.idle

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.View
import android.widget.ImageView
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.odm.communitymanage.R
import com.odm.communitymanage.util.Utils
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.util.GlideUtils
import com.rxjava.rxlife.RxLife
import com.rxjava.rxlife.lifeOnMain
import com.zhihu.matisse.Matisse
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_post_idle.*
import rxhttp.wrapper.param.RxHttp
import java.io.File

/**
 * @description: 发布闲置页面
 * @author: ODM
 * @date: 2020/4/12
 */
class PostIdleFragment : BaseMVVMFragment() {

    var disposable :Disposable ?= null

    var photoUris: MutableList<Uri>  ?= mutableListOf()

    override fun initViewModelObserve() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
    }

    override fun initViews() {
        btnPostIdlePhoto.setOnClickListener {
            //跳转页面选择图片，当选择了图片后，依次让iv1,iv2,iv3 设为Visible，iv3也可见后将添加图片按钮设为inVisible！
            Utils.openMatissePage(this)
        }

        //提交上传信息按钮
        btnPostIdleInfo.setOnClickListener {
            val topic = etTopic_PostIdle.text.toString()
            val price = etPrice_PostIdle.text.toString()
            val  desc = etDescription_PostIdle.text.toString()
            val remarks = etRemark_PostIdle.text.toString()
            var userName =   etContactName_PostIdle.text.toString()
            var phone = etPhoneNumber_PostIdle.text.toString()
            if(phone == ""){
                phone = SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_PHONE_NUMBER)
            }
            if(userName == ""){
                userName = SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_NAME)
            }
            hideSoftInput()
            //调用上传 闲置信息
            postIdleInfo(topic,price,desc,userName,phone,photoUris,remarks)

        }


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //加载从 图库中选择的图片，每次为多张或单张，最多放入3张
        if (requestCode == Constants.REQUEST_IMAGE_CODE && data != null) {
            val result = Matisse.obtainResult(data)
            val uriList: MutableList<Uri> ? = result
            uriList?.let {
                for (uri in uriList ) {
                    var target : ImageView ?= null
                    if (ivPhoto_1_PostIdle.visibility != View.VISIBLE) {
                        target = ivPhoto_1_PostIdle
                    } else if (ivPhoto_2_PostIdle.visibility != View.VISIBLE) {
                        target = ivPhoto_2_PostIdle
                    } else if (ivPhoto_3_PostIdle.visibility != View.VISIBLE) {
                        target = ivPhoto_3_PostIdle
                        btnPostIdlePhoto.visibility = View.INVISIBLE
                    }
                    target?.let {
                        GlideUtils.getInstance()
                            .loadImageUri(requireContext(), uri, target)
                        target.visibility = View.VISIBLE
                        //添加进上传图片的Uri列表
                        photoUris?.add(uri)
                    }
                }

            }
        }
    }

    /**
     * 上传 闲置表单 信息
     * @param topic String
     * @param price String
     * @param desc String
     * @param userName String
     * @param phone String
     * @param photos MutableList<File>
     * @param remarks String
     */
    private  fun postIdleInfo(topic:String = "无标题", price: String = "0", description:String = "无描述",
                              userName:String ,
                              phone:String,
                              photos:MutableList<Uri>?, remarks:String = ""){
        if(topic == "" || price == ""){
            ToastUtils.showShort("请填写 标题与价格")
            return
        }
        if(photos?.isEmpty() == true){
            ToastUtils.showShort("请选择合适的图片")
            return
        }
        val param = RxHttp.postForm(ApiService.POST_MY_IDLE)
            .add("topic",topic)
            .add("price",price)
            .add("description",description)
            .add("userName",userName)
            .add("phone",phone)
            .add("remarks",remarks)
        //添加文件
        photos?.let {
            for(uri in photos){
                val photo = Utils.getPhotoFileByUri(uri,true)
                param.addFile("file",photo)
            }
        }

        disposable = param.upload {
            LogUtils.d("上传进度:  ${it.progress}")
        }.asClass(NetCallBack::class.java)
            .lifeOnMain(this)
            .subscribe({
                if(it.code != 1){
                    ToastUtils.showShort(it.message)
                }else {
                    //上传成功
                    showSuccessSnack(getString(R.string.post_success))
                    //返回上一页面
                    pop()
                }
            },{
                //出现异常
                LogUtils.e("上传异常 "+ it.localizedMessage)
                ToastUtils.showShort(it.message)
                it.printStackTrace()
            })


    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_post_idle
    }
}